<template>
  <div class="conversation-import" :class="{ 'dark': isDarkMode }">
    <div class="upload-area" :class="{ 'drag-over': isDragOver }" @drop.prevent="handleDrop" @dragover.prevent="isDragOver = true" @dragleave="isDragOver = false">
      <div class="upload-content">
        <div class="upload-icon">
          <i class="fas fa-cloud-upload-alt"></i>
        </div>
        <div class="upload-text">
          <h3>导入对话内容</h3>
          <p>拖放文件到此处或</p>
          <button class="upload-button" @click="triggerFileInput">选择文件</button>
          <input type="file" ref="fileInputRef" @change="handleFileChange" accept=".txt" style="display: none">
        </div>
      </div>
    </div>

    <div class="text-input-area">
      <h3>或直接输入对话内容</h3>
      <div class="processing-time-notice">
        <i class="fas fa-clock"></i>
        <span>处理时间说明：分析时长取决于对话内容的长度，一般情况下：</span>
        <ul>
          <li>10回合对话：约2分钟</li>
          <li>20回合对话：约4分钟</li>
        </ul>
      </div>
      <div class="input-controls">
        <textarea
          v-model="directInput"
          placeholder="请输入需要分析的对话内容..."
          rows="10"
          class="text-input"
          :disabled="analyzing"
        ></textarea>
      </div>
    </div>

    <div class="action-buttons" v-if="directInput">
      <button 
        class="analyze-button" 
        :disabled="analyzing || !directInput" 
        @click="startAnalysis"
      >
        <i class="fas fa-chart-line"></i>
        {{ analyzing ? '分析中...' : '开始分析' }}
      </button>
      <button 
        class="clear-button" 
        :disabled="analyzing" 
        @click="clearContent"
      >
        <i class="fas fa-trash-alt"></i>
        清除内容
      </button>
    </div>

    <div v-if="analyzing" class="progress-section">
      <h3>分析进度</h3>
      <div class="progress-container">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${progressPercentage}%` }"></div>
        </div>
        <div class="progress-steps">
          <div 
            v-for="(step, index) in analysisSteps" 
            :key="step.id"
            class="progress-step"
            :class="{ 'completed': completedSteps.includes(step.id) }"
          >
            <div class="step-marker">{{ index + 1 }}</div>
            <div class="step-name">{{ step.name }}</div>
          </div>
        </div>
      </div>
      <div class="current-step-info" v-if="currentStep">
        <p>当前步骤: <strong>{{ currentStep.name }}</strong> - {{ currentStep.description }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRoute } from 'vue-router';
import type { AnalysisResult, ConversationMessage } from '../../types/dialogue';
import DialogueAnalysisWebSocket, { analysisSteps, type AnalysisStep } from '../../api/dialogueAnalyze';

const route = useRoute();
const fileInputRef = ref<HTMLInputElement | null>(null);
const directInput = ref('');
const isDragOver = ref(false);
const isDarkMode = ref(false);
const analyzing = ref(false);
const completedSteps = ref<string[]>([]);
const currentStep = ref<AnalysisStep | null>(null);
const websocket = ref<DialogueAnalysisWebSocket | null>(null);

const emit = defineEmits<{
  (e: 'analysis-complete', result: AnalysisResult): void
}>();

// 示例对话内容
const demoConversation = `A（女）： 你怎么又忘了我们今天要一起吃饭？我提前跟你说过了啊！

B（男）： 啊？我不是故意的，今天工作真的太忙了，实在是没时间啊。

A： 忘就不能回个消息吗？我给你发了好几条信息，你一条都没回！

B： 我是真的没看到手机……事情太多，根本顾不上看消息。

A： 你每次都这么说，那我呢？我就不重要吗？

B： 不是这个意思……我真的很在乎你！只是工作真的压得我喘不过气。

A： 可是你有没有想过，我也需要被在乎？

B（沉默了一下）： ……对不起，我以后会注意的，真的。

A（叹气）： 这次我相信你，但希望你说到做到。`;

const progressPercentage = computed(() => {
  return (completedSteps.value.length / analysisSteps.length) * 100;
});

const initWebSocket = async () => {
  if (websocket.value) {
    websocket.value.disconnect();
  }
  
  websocket.value = new DialogueAnalysisWebSocket();
  
  return new Promise<void>((resolve, reject) => {
    websocket.value?.connect({
      onProgress: (step) => {
        currentStep.value = step;
        if (!completedSteps.value.includes(step.id)) {
          completedSteps.value.push(step.id);
        }
      },
      onResult: (result) => {
        analyzing.value = false;
        emit('analysis-complete', result);
      },
      onError: (error) => {
        analyzing.value = false;
        alert(`分析失败: ${error}`);
        reject(error);
      },
      onClose: () => {
        analyzing.value = false;
      },
      onOpen: () => {
        console.log('WebSocket connection established');
        resolve();
      }
    });
  });
};

const startAnalysis = async () => {
  if (!directInput.value.trim()) {
    alert('请输入对话内容');
    return;
  }

  try {
    analyzing.value = true;
    completedSteps.value = [];
    currentStep.value = null;

    // 确保 WebSocket 连接已建立
    if (!websocket.value?.isConnected()) {
      await initWebSocket();
    }

    // 发送分析请求
    websocket.value?.sendAnalysis(directInput.value);
  } catch (error) {
    analyzing.value = false;
    alert(`分析过程中发生错误: ${error instanceof Error ? error.message : String(error)}`);
    console.error('Analysis error:', error);
  }
};

onMounted(async () => {
  isDarkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
    isDarkMode.value = e.matches;
  });
  
  try {
    await initWebSocket();
  } catch (error) {
    console.error('Failed to initialize WebSocket:', error);
  }
  
  // 检查URL参数，如果有demo=true参数，则自动填充示例对话内容
  if (route.query.demo === 'true') {
    directInput.value = demoConversation;
    // 自动开始分析
    setTimeout(() => {
      startAnalysis();
    }, 800); // 延迟800毫秒开始分析，给用户一个看到对话内容的机会
  }
});

onUnmounted(() => {
  websocket.value?.disconnect();
});

const triggerFileInput = () => {
  fileInputRef.value?.click();
};

const clearContent = () => {
  directInput.value = '';
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
  completedSteps.value = [];
  currentStep.value = null;
};

const handleFileChange = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    const text = await file.text();
    directInput.value = text;
  }
};

const handleDrop = async (event: DragEvent) => {
  isDragOver.value = false;
  const files = event.dataTransfer?.files;
  if (files && files[0]) {
    const file = files[0];
    if (file.type === 'text/plain') {
      const text = await file.text();
      directInput.value = text;
    }
  }
};
</script>

<style lang="scss" scoped>
.conversation-import {
  padding: 20px;
  width: 60%;
  
  .upload-area {
    border: 2px dashed var(--border-color, #8b5cf6);
    border-radius: 8px;
    padding: 40px;
    text-align: center;
    transition: all 0.3s ease;
    background: var(--upload-bg, rgba(139, 92, 246, 0.05));
    margin-bottom: 20px;

    &.drag-over {
      background: var(--upload-bg-hover, rgba(139, 92, 246, 0.1));
      border-color: var(--border-color-hover, #6d28d9);
    }

    .upload-icon {
      font-size: 48px;
      color: var(--icon-color, #8b5cf6);
      margin-bottom: 16px;
    }

    .upload-text {
      h3 {
        margin: 0 0 8px;
        color: var(--text-primary, #4b5563);
      }

      p {
        margin: 0 0 16px;
        color: var(--text-secondary, #6b7280);
      }
    }
  }

  .text-input-area {
    margin: 20px 0;

    h3 {
      margin: 0 0 12px;
      color: var(--text-primary, #4b5563);
    }

    .processing-time-notice {
      margin-bottom: 16px;
      padding: 12px;
      background-color: var(--info-bg, rgba(139, 92, 246, 0.05));
      border-radius: 6px;

      i {
        margin-right: 8px;
        color: var(--icon-color, #8b5cf6);
      }

      span {
        font-size: 14px;
        color: var(--text-primary, #4b5563);
      }

      ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          font-size: 14px;
          color: var(--text-secondary, #6b7280);
        }
      }
    }

    .input-controls {
      .text-input {
        width: 100%;
        padding: 12px;
        border: 1px solid var(--border-color, #e5e7eb);
        border-radius: 6px;
        resize: vertical;
        font-family: inherit;
        background: var(--input-bg, white);
        color: var(--text-primary, #4b5563);
        
        &:focus {
          outline: none;
          border-color: var(--border-color-focus, #8b5cf6);
          box-shadow: 0 0 0 2px var(--focus-ring, rgba(139, 92, 246, 0.2));
        }

        &:disabled {
          background-color: var(--input-bg-disabled, #f3f4f6);
          cursor: not-allowed;
        }

        &::placeholder {
          color: var(--text-placeholder, #9ca3af);
        }
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: 12px;
    margin: 20px 0;

    button {
      padding: 8px 16px;
      border-radius: 6px;
      font-weight: 500;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      gap: 8px;
      
      i {
        font-size: 14px;
      }
      
      &:disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }

    .analyze-button {
      background: var(--button-primary-bg, #8b5cf6);
      color: white;
      border: none;
      
      &:hover:not(:disabled) {
        background: var(--button-primary-bg-hover, #7c3aed);
      }
    }

    .clear-button {
      border: 1px solid var(--border-color, #e5e7eb);
      background: var(--button-secondary-bg, white);
      color: var(--text-primary, #4b5563);
      
      &:hover:not(:disabled) {
        background: var(--button-secondary-bg-hover, #f3f4f6);
      }
    }
  }

  .progress-section {
    margin-top: 30px;
    
    h3 {
      margin: 0 0 12px;
      color: var(--text-primary, #4b5563);
    }
    
    .progress-container {
      margin-bottom: 20px;
    }
    
    .progress-bar {
      height: 8px;
      background-color: var(--progress-bg, #e5e7eb);
      border-radius: 4px;
      margin-bottom: 15px;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background: linear-gradient(to right, #8b5cf6, #6d28d9);
        transition: width 0.5s ease;
      }
    }
    
    .progress-steps {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      
      .progress-step {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        
        &.completed {
          .step-marker {
            background-color: #6d28d9;
            color: white;
          }
          
          .step-name {
            color: #6d28d9;
            font-weight: 600;
          }
        }
        
        .step-marker {
          width: 28px;
          height: 28px;
          border-radius: 50%;
          background-color: var(--step-marker-bg, #e5e7eb);
          color: var(--step-marker-color, #6b7280);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          font-weight: 600;
          margin-bottom: 8px;
          transition: all 0.3s ease;
        }
        
        .step-name {
          font-size: 12px;
          color: var(--text-secondary, #6b7280);
          text-align: center;
          transition: all 0.3s ease;
        }
      }
    }
    
    .current-step-info {
      padding: 10px;
      background-color: var(--info-bg, rgba(139, 92, 246, 0.05));
      border-radius: 6px;
      
      p {
        margin: 0;
        color: var(--text-primary, #4b5563);
        font-size: 14px;
      }
    }
  }
}

.upload-button {
  background: var(--button-primary-bg, #8b5cf6);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.2s ease;

  &:hover {
    background: var(--button-primary-bg-hover, #7c3aed);
  }
}

// Dark mode styles
.dark {
  --text-primary: #e5e7eb;
  --text-secondary: #9ca3af;
  --text-placeholder: #6b7280;
  --border-color: #374151;
  --border-color-hover: #4b5563;
  --border-color-focus: #8b5cf6;
  --upload-bg: rgba(139, 92, 246, 0.1);
  --upload-bg-hover: rgba(139, 92, 246, 0.15);
  --icon-color: #8b5cf6;
  --input-bg: #1f2937;
  --input-bg-disabled: #374151;
  --button-primary-bg: #7c3aed;
  --button-primary-bg-hover: #6d28d9;
  --button-secondary-bg: #374151;
  --button-secondary-bg-hover: #4b5563;
  --progress-bg: #374151;
  --step-marker-bg: #4b5563;
  --step-marker-color: #e5e7eb;
  --info-bg: rgba(139, 92, 246, 0.1);
  --focus-ring: rgba(139, 92, 246, 0.3);
}

@media (max-width: 768px) {
  .conversation-import {
    padding: 16px;

    .upload-area {
      padding: 24px;

      .upload-icon {
        font-size: 36px;
      }
    }

    .text-input-area {
      .text-input {
        font-size: 14px;
      }
    }

    .action-buttons {
      flex-direction: column;

      button {
        width: 100%;
      }
    }
    
    .progress-section {
      .progress-steps {
        .progress-step {
          .step-name {
            font-size: 10px;
          }
        }
      }
    }
  }
}
</style>
